//
//  ST_AISortMyPeculiarityController.swift
//  btvideo
//
//  Created by mac on 2020/3/20.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import KDDragAndDropCollectionViews
import HandyJSON
import TZImagePickerController
import SwiftyUserDefaults

//编辑特质顺序 - Controller
class ST_AISortMyPeculiarityController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("排列特质图片")
        
         
        
        view.backgroundColor = Color.clear
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
        }
        
        
        self.drag_and_drop_manager = KDDragAndDropManager.init(canvas: self.view, collectionViews: [collectionView])
        
        
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    
        let sortedArray = data_array+checkingDataArray
        
        self.sort_closure?(sortedArray)
        
        ST_MyPeculiaritySortManager.shared.dis_appear_hanlde(data_array: sortedArray)
        
    }
    

    //    MARK: - block
    
    var sort_closure:(([ST_SingleHumanST_PeculiarityCellModel])->())?
    //    MARK: - Data Array
    
    /**
     外部传递的数据
     */
    var prepareSortArray = [ST_SingleHumanST_PeculiarityCellModel](){
        didSet{
         
            self.data_array = self.prepareSortArray.filter { (m) -> Bool in
                return m.state != 1
            }
            self.checkingDataArray = self.prepareSortArray.filter { (m) -> Bool in
                return m.state == 1
            }
            
        }
    }
    
    fileprivate lazy var data_array = [ST_SingleHumanST_PeculiarityCellModel]()
    
    fileprivate lazy var checkingDataArray = [ST_SingleHumanST_PeculiarityCellModel]()
    
    
//    MARK: - properties
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
       let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumInteritemSpacing = 6
        controlLayout.minimumLineSpacing = 6
        controlLayout.sectionInset = UIEdgeInsets.init(top: 13, left: 15, bottom: BTSafeAreaBottom + 100, right: 15)
        controlLayout.itemSize = cellSize
        return controlLayout
    }()
    
    fileprivate lazy var itemWidth:CGFloat = {
        return  ((ScreenWidth - 30 - 6*3)/4.0).int.cgFloat
    }()
    
    fileprivate lazy var cellSize = CGSize.init(width:itemWidth, height:itemWidth/8.0*10.0)
    
//
    
    fileprivate lazy var collectionView:KDDragAndDropCollectionView = {
        let control = KDDragAndDropCollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_SortMyPecCell.self)
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_MyPhotoCollectionReusableView.self)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = Color.white
        
        control.alwaysBounceVertical = true
        
        return control
    }()
    
    fileprivate var drag_and_drop_manager : KDDragAndDropManager?

    
    
 
}


extension ST_AISortMyPeculiarityController:KDDragAndDropCollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
//    MARK:- 拖拽移动
    
    func collectionView(_ collectionView: UICollectionView, cellIsDraggableAtIndexPath indexPath: IndexPath) -> Bool {
        
        return true
    }
    func collectionView(_ collectionView: UICollectionView, cellIsDroppableAtIndexPath indexPath: IndexPath) -> Bool {
       return true
    }
    
    func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath: IndexPath) {
        
        data_array.remove(at: indexPath.item)
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem: AnyObject, atIndexPath indexPath: IndexPath) {
        
        data_array.insert(dataItem as! ST_SingleHumanST_PeculiarityCellModel, at: indexPath.item)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to: IndexPath) {
        
        let fromDataItem = data_array[from.item]
        
        data_array.remove(at: from.item)
        
        data_array.insert(fromDataItem, at: to.item)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject {
        return data_array[indexPath.item] as AnyObject
    }
    
    
    func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath? {
        
        if let item =  dataItem as? ST_SingleHumanST_PeculiarityCellModel{
            
            let f = data_array.firstIndex { (i) -> Bool in
                return i == item
            }
            
            if let idx = f{
                
                let r = Int(idx)
                
                return IndexPath.init(row: r, section: 0)
            }
        }
        
        return nil
    }
    
//    MARK:- 数据源&&delegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return cellSize
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
       
        let cell = collectionView.dequeueReusableCell(withClass: ST_SortMyPecCell.self, for: indexPath)
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        
        cell.isHidden = false
        
        if let kdCollectionView = collectionView as? KDDragAndDropCollectionView {
            
            if let draggingPathOfCellBeingDragged = kdCollectionView.draggingPathOfCellBeingDragged {
                
                if draggingPathOfCellBeingDragged.item == indexPath.item {
                    
                    cell.isHidden = true
                    
                }
            }
        }
        
        cell.is_cover_sign_view.isHidden = indexPath.row != 0
        
        return cell
    }
}
//MARK: - Cell
fileprivate class ST_SortMyPecCell:UICollectionViewCell{
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .white
        contentView.addSubview(cover_image_view)
        contentView.addSubview(drag_image_view)
        contentView.addSubview(is_cover_sign_view)
        
        cover_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        drag_image_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(drag_image_view.snp.width).dividedBy(3)
            make.bottom.equalToSuperview().offset(-5)
        }
        
        is_cover_sign_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(20)
            make.right.equalToSuperview().offset(-5)
            make.top.equalToSuperview().offset(5)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK:

    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 10
        return control
    }()


    fileprivate lazy var drag_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("特质_icon_拖动")!)
        return control
    }()
    
    fileprivate lazy var is_cover_sign_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("特质_icon_封面")!)
        control.isHidden = true
        return control
    }()
    
    var model = ST_SingleHumanST_PeculiarityCellModel(){
        didSet{
            
            cover_image_view.pin_setImage(from: model.content.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        }
    }
}


//MARK: - Sort


fileprivate class ST_MyPeculiaritySortManager: NSObject {
    
    static let  shared = ST_MyPeculiaritySortManager()
    
    
    func dis_appear_hanlde(data_array:[ST_SingleHumanST_PeculiarityCellModel]) {
        
        
        let uploadedArray = data_array.map { (m) -> String in
            return m.id.string
        }
        
        let str = uploadedArray.joined(separator: ",")
        
        
        let param = ["content_ids":str]
        
        JVrequest(PH.sortMyPeculiarityApi, parameters : param ,success: { (json) in
            
            print("排序特质成功")
            
        }) { (code, err) in
            print("排序特质失败：",err)
        }
        
        
        
    }
    
}
